<?php
namespace Controllers;

use Models\CategoryModel;
use Models\PostModel;
use Models\UserModel;

class CommonController
{
    public function response($tpl, $data = [])
    {
        $file = './Views/' . $tpl . '.tpl.php';
        if (!file_exists($file)) exit('模板文件' . $file . '不存在');
        $cateModel = new CategoryModel();
        $navList = $cateModel->getAllCategories();
        $userModel = new UserModel();
        $activeUsers = $userModel->getActiveUser();
        $postModel = new PostModel();
        $hotPosts = $postModel->getHotPosts();
        $data['navList'] = $navList;
        $data['activeUsers'] = $activeUsers;
        $data['hotPosts'] = $hotPosts;
        extract($data);
        require_once $file;
    }

    public function responseJson($status, $message = '', $data = []) {
        $result = compact('status', 'message', 'data');
        return json_encode($result);
    }

    protected function isLogin() {
        if (isset($_SESSION['user_id']) && isset($_SESSION['username'])) {
            return true;
        } else {
            return false;
        }
    }

    protected function loginJump() {
        if ($this->isLogin()) {
            echo '<script>window.location.href="/"</script>';exit;
        }
    }

    protected function noLoginJump() {
        if (!$this->isLogin()) {
            echo '<script>window.location.href="/index.php?c=user&a=login"</script>';exit;
        }
    }
}